﻿#include "CustomTreeViewModel.h"

CustomTreeViewModel::CustomTreeViewModel(QObject *parent) : QStandardItemModel(parent)
{
    setHorizontalHeaderLabels(QStringList() << "文件名/表名");
}

CustomTreeViewModel::~CustomTreeViewModel()
{
}

bool CustomTreeViewModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if (!index.isValid())
        return false;
    QStandardItemModel::setData(index, value, role);
    if (role == Qt::CheckStateRole)
    {
        updateCheckState(index);
    }

    return true;
}

Qt::ItemFlags CustomTreeViewModel::flags(const QModelIndex &index) const
{
    Qt::ItemFlags flags = QStandardItemModel::flags(index);
    return flags | Qt::ItemIsUserCheckable;
}

void CustomTreeViewModel::setFileData(fileNodeInfo *node)
{
    m_fileNodeinfo = node;
    addData(m_fileNodeinfo, nullptr);
}

void CustomTreeViewModel::updateCheckState(const QModelIndex &index)
{
    QStandardItem *item = itemFromIndex(index);
    if (item)
    {
        QVariant data = item->data(Qt::CheckStateRole);
        if (data.isValid())
        {
            Qt::CheckState state = static_cast<Qt::CheckState>(data.toInt());
            bool isChecked = (state == Qt::Checked);

            // 从模型索引中获取 fileNodeInfo 指针
            fileNodeInfo *nodeInfo = reinterpret_cast<fileNodeInfo *>(item->data(Qt::UserRole).value<void *>());
            if (nodeInfo)
            {
                // 更新 fileNodeInfo 的 bcheck 字段
                nodeInfo->bcheck = isChecked;
            }
        }
    }
}

void CustomTreeViewModel::addData(fileNodeInfo *data, QStandardItem *parent)
{
    QStandardItem *rootNode = nullptr;
    if (parent == nullptr)
    {
        rootNode = invisibleRootItem();
    }
    else
    {
        rootNode = parent;
    }
    QStandardItem *parentNode = new QStandardItem(data->name);
    rootNode->appendRow(parentNode);
    parentNode->setCheckable(true);
    auto checkStatus = data->bcheck ? Qt::Checked : Qt::Unchecked;
    parentNode->setCheckState(checkStatus);
    if (data->m_childNode.size() != 0)
    {
        for (int i = 0; i < data->m_childNode.size(); ++i)
        {
            addData(&data->m_childNode[i], parentNode);
        }
    }
}
